package threading;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-03-26
 * Time: 18:17
 */
class Counter {
    private int count = 0;

//    public void add() {
//        synchronized (this) {
//            count++;
//        }
//    }

    //如果直接给方法使用synchronized修饰，此时就相当于以this为锁对象
    synchronized public void add() {
            count++;
    }

    public int getCount() {
        return count;

    }
}

public class ThreadExample_unsafe {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });
        t1.start();
        t2.start();

        //等两个线程结束后查看结果
        t1.join();
        t2.join();

        System.out.println(counter.getCount());
    }
}
